import { isFunction, isObject, isArray } from './is'
/**
 * @description 复制文本
 * @param text
 */
export const copyText = (text: string) => new Promise((resolve) => {
  // 创建input框获取需要复制的文本内容
  const copyInput = document.createElement('input')
  copyInput.value = text
  document.body.appendChild(copyInput)
  copyInput.select()
  document.execCommand('copy')
  copyInput.remove()
  resolve(true)
})

/**
 * @description 深度克隆
 * @param obj 克隆对象
 * @returns _obj 经过克隆之后的对象
 */
export const cloneDeep = function (obj: any) {
  // 常见的非值直接返回
  if ([null, undefined, NaN, false].includes(obj)) return obj
  // 原始类型直接返回
  if (!isFunction(obj) && !isObject(obj)) return obj
  const o: any = isArray(obj) ? [] : {}
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      o[key] = isObject(obj[key]) ? cloneDeep(obj[key]) : obj[key]
    }
  }
  return o
}

/**
 * @description 对象转string
 * @param obj 克隆对象
 * @returns string 经过转换之后的string
 */
export const toJSON = function (obj: any) {
  return JSON.stringify(obj, (key, value) => {
    switch (true) {
      case typeof value === 'undefined':
        return 'undefined'
      case typeof value === 'symbol':
        return value.toString()
      case typeof value === 'function':
        return value.toString()
      default:
        break
    }
    return value
  })
}

/**
 * @description 将对象当作参数拼接到url上
 * @param baseUrl 需要拼接的url
 * @param obj 参数对象
 * @returns {string} 拼接后的对象
 * 例子:
 *  let obj = {a: '1', b: '2'}
 *  setObjToUrlParams('www.baidu.com', obj)
 *  ==>www.baidu.com?a=3&b=4
 */
export const setObjToUrlParams = function(baseUrl: string, obj: any) {
  let parameters = ''
  let url = ''
  for (const key in obj) {
    parameters += key + '=' + encodeURIComponent(obj[key]) + '&'
  }
  parameters = parameters.replace(/&$/, '')
  if (/\?$/.test(baseUrl)) {
    url = baseUrl + parameters
  } else {
    url = baseUrl.replace(/\/?$/, '?') + parameters
  }
  return url
}

/**
 * @description 浏览器全屏\非全屏切换
 * @param fullElement
 */
export const screenFull = function (fullElement = document.documentElement) {
  // 判断是否处在全屏状态
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  const isFullScreen = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
  if (isFullScreen) {
    const el = document
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const cfs = el.cancelFullScreen || el.mozCancelFullScreen || el.msExitFullscreen || el.webkitExitFullscreen || el.exitFullscreen
    cfs && cfs.call(el)
  } else {
    const el = fullElement
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    const rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreen
    rfs && rfs.call(el)
  }
}
